/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.business.account.core.service.processor.active;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import info.peigen.hotpot.business.account.core.domain.account.Account;
import info.peigen.hotpot.business.account.core.domain.account.AccountTransfer;
import info.peigen.hotpot.business.account.core.service.processor.base.AbstractAccountServiceProcessor;
import info.peigen.hotpot.business.account.facade.enums.AccountTransCode;
import info.peigen.hotpot.business.account.facade.order.trans.TransferOrder;
import info.peigen.hotpot.common.core.lang.money.Money;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import org.noear.solon.annotation.Component;

import java.util.Date;

/**
 * <b>(ActiveTransferAccountProcessor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/5/26
 */
@Component
public class ActiveTransferAccountProcessor extends AbstractAccountServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 11;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        TransferOrder order = (TransferOrder) serviceContext.getOrder();

        Account payerAccount = accountRepository.active(order.getPayerAccountId());
        Assert.notNull(payerAccount, () -> new BusinessException(ResultCode.FAILURE, "未能锁定账户[accountId=" + order.getPayerAccountId() + "]"));
        payerAccount.check();
        Account payeeAccount = accountRepository.active(order.getPayeeAccountId());
        Assert.notNull(payeeAccount, () -> new BusinessException(ResultCode.FAILURE, "未能锁定账户[accountId=" + order.getPayeeAccountId() + "]"));
        payeeAccount.check();
        AccountTransfer transfer = BeanUtil.copyProperties(order, AccountTransfer.class)
                .setTransCode(AccountTransCode.Transfer)
                .setPayerAccount(payerAccount)
                .setPayeeAccount(payeeAccount)
                .setHistoryPayerBalance(new Money(payerAccount.getBalance()))
                .setHistoryPayeeBalance(new Money(payeeAccount.getBalance()))
                .setHistoryFeePayerBalance(new Money(payerAccount.getBalance()))
                .setSettleTime(new Date());

        serviceContext.setDomain(transfer);
    }

}
